<?php
namespace app\common\model;

use think\Model;
use think\Loader;

class Terms extends Model
{
    public function saveTerms($data,$id='')
    {
        $datas['term_pid']    = $data['term_pid'];
        $datas['name']        = $data['name'];
        $datas['description'] = $data['description'];
        if($id){
        	$res = $this->where('name',$datas['name'])->where('term_id','<>',$id)->find();
        	if($res){
        		$msg['code']='0';
        		$msg['msg']='分类名重复';
        		return $msg;
        	}
        	$res = $this->where($datas)->where('term_id',$id)->find();
        	if($res){
        		$msg['code']='1';
        		$msg['msg']='更新成功';
        		return $msg;
        	}
        	$res = $this->where('term_id',$id)->update($datas);
        }else{
        	$res = $this->where('name',$datas['name'])->find();
        	if($res){
        		$msg['code']='0';
        		$msg['msg']='分类名重复';
        		return $msg;
        	}
        	$res = $this->insertGetId($datas);
        }
        if($res){
        	$msg['code']='1';
        	$msg['msg']='保存成功';
        }else{
        	$msg['code']='0';
        	$msg['msg']='保存失败';
        }
        return $msg;
    }
    /**
     * 根据对象id获取分类信息
     * @param  [type] $new_id [description]
     * @return [type]         [description]
     */
    public function getTermForObjectId($new_id)
    {
        $tr = Loader::model('TermRelationships');
        $res = $tr->where('object_id',$new_id)->find();
        if($res){
            return $res;
        }
        return false;
    }
}
